/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.antcloud.demo.antscheduler.nine1nine;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

import com.alibaba.fastjson.JSON;

import com.alipay.antschedulerclient.common.ClientCommonResult;
import com.alipay.antschedulerclient.handler.ISimpleJobHandler;
import com.alipay.antschedulerclient.model.JobExecuteContext;
import com.antcloud.demo.antscheduler.dal.daointerface.BillItemDAO;
import com.antcloud.demo.antscheduler.dal.dataobject.BillItemDO;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 * @author qian.lqlq
 * @version $Id: BillNotify.java, v 0.1 2018年09月05日 21:36 qian.lqlq Exp $
 */
public class BillNotify implements ISimpleJobHandler {

    @Autowired
    private BillItemDAO billItemDAO;

    @Override
    public ClientCommonResult handle(JobExecuteContext context) throws Exception {
        Map<String, PushMsg> msgMap = Maps.newHashMap();
        Map<String, Bill> billMap = Maps.newHashMap();
        List<BillItemDO> billItemDOList = billItemDAO.getAll();
        Calendar calendar = Calendar.getInstance();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        for (BillItemDO billItemDO : billItemDOList) {
            String userId = billItemDO.getUserId();
            if (!billMap.containsKey(userId)) {
                billMap.put(userId, new Bill(userId, date));
            }
            Bill bill = billMap.get(userId);
            BillItemTypeEnum type = BillItemTypeEnum.valueOf(billItemDO.getType());
            long amount = billItemDO.getAmount();
            switch (type) {
                case EXPAND:
                    bill.addExpand(amount);
                    break;
                case INCOME:
                    bill.addIncome(amount);
                    break;
                case BALANCE:
                    bill.addBalance(amount);
                    break;
                default:
                    break;
            }
        }
        for (String userId : billMap.keySet()) {
            Bill bill = billMap.get(userId);
            if (bill.getExpand() > 0L || bill.getIncome() > 0L) {
                msgMap.put(userId, new PushMsg(userId, PushMsgTypeEnum.BILL, billMap.get(userId)));
            }
        }
        if (!msgMap.isEmpty()) {
            WebSocketServer.sendMessage(msgMap);
        }
        return ClientCommonResult.buildSuccessResult();
    }

    @Override
    public String getName() {
        return "billNotify";
    }

    @Override
    public ThreadPoolExecutor getThreadPool() {
        return null;
    }
}